package middleware

import (
	"net/http"
	"one-api/model"
	"one-api/service"
	"strings"

	"github.com/gin-gonic/gin"
)

// APIForwardMiddleware API转发中间件
func APIForwardMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求路径并去除首尾空白（处理意外的制表符/空格）
		path := strings.TrimSpace(c.Request.URL.Path)

		// 检查是否需要转发
		apiForwardService := &service.APIForwardService{}
		_, err := model.GetForwardConfigByPath(path)
		if err != nil {
			// 没有找到转发配置，继续正常流程
			c.Next()
			return
		}

		// 需求1：必须 token 鉴权（内联验证，不触发后续中间件，避免重复处理）
		if !inlineTokenAuth(c) {
			return
		}

		// 如果找到转发配置，执行转发
		newAPIError := apiForwardService.ForwardRequest(c, path)
		if newAPIError != nil {
			// 转发失败，返回错误
			c.JSON(newAPIError.StatusCode, gin.H{
				"error": gin.H{
					"message": newAPIError.Error(),
					"type":    "api_forward_error",
					"code":    newAPIError.GetErrorCode(),
				},
			})
			c.Abort()
			return
		}

		// 转发成功，请求已处理，不再继续
		c.Abort()
	}
}

// inlineTokenAuth 提取并校验 Token，不调用 c.Next()，避免继续后续链路产生重复日志
func inlineTokenAuth(c *gin.Context) bool {
	// 仅处理常见 Authorization: Bearer sk-***
	auth := c.Request.Header.Get("Authorization")
	key := strings.TrimPrefix(auth, "Bearer ")
	key = strings.TrimPrefix(key, "sk-")
	if key == "" {
		abortWithOpenAiMessage(c, http.StatusUnauthorized, "未提供令牌")
		return false
	}
	parts := strings.Split(key, "-")
	key = parts[0]

	token, err := model.ValidateUserToken(key)
	if err != nil || token == nil {
		abortWithOpenAiMessage(c, http.StatusUnauthorized, "无效的令牌")
		return false
	}
	userCache, err := model.GetUserCache(token.UserId)
	if err != nil {
		abortWithOpenAiMessage(c, http.StatusInternalServerError, err.Error())
		return false
	}
	if userCache.Status != 1 {
		abortWithOpenAiMessage(c, http.StatusForbidden, "用户已被封禁")
		return false
	}
	if err := SetupContextForToken(c, token, parts...); err != nil {
		return false
	}
	return true
}
